package com.leo.customer.entity.pojo

import com.auth0.jwt.JWT
import com.auth0.jwt.algorithms.Algorithm
import com.leo.customer.Constants
import com.leo.customer.entity.CreateTimeAndUpdateTime
import org.springframework.beans.BeanUtils
import javax.persistence.*
import javax.validation.constraints.*

@Entity
@Table(uniqueConstraints = [UniqueConstraint(columnNames = arrayOf("phone"))])
data class User(
//        @field:NotBlank(message = "用户名不能为空")
    var userName: String = "",
    @field:Pattern(regexp = "^(?:(?:\\+|00)86)?1[3-9]\\d{9}$", message = "请输入正确手机号")
    @Column(name = "phone")
    var phone: String = "",
    var pwd: String = "",
    @field:Max(value = 2, message = "gender不能大于2")
    var gender: Int = 0,
    var age: Int = 0,
    var identityNumber: String = "",
    /**
     * 用户权限
     */
    @ManyToMany(targetEntity = UserRole::class, cascade = [CascadeType.ALL], fetch = FetchType.LAZY)
    @JoinTable(name = "sys_role_user")
    var userRoles: MutableList<UserRole> = mutableListOf()
) : CreateTimeAndUpdateTime() {
    fun getToken(): String {
        return JWT.create().withAudience(id.toString())
            .sign(Algorithm.HMAC256(Constants.Token_Secret_Key))
    }

    fun convertToVo(): UserVo {
        val userVo = UserVo()
        BeanUtils.copyProperties(this, userVo)
        return userVo
    }

    fun hasAuthenticate(): Boolean {
        return userName.isNotBlank() && identityNumber.isNotBlank()
    }
}

data class UserVo(
    var userName: String = "",
    var phone: String = "",
    var token: String = "",
    var id: Int = 0
)
